"""
消息去重模块
使用内存缓存防止重复处理同一条消息
"""
import time
import threading
from typing import Dict, Set, Optional, Tuple
from common.log import logger


class MessageDeduplicator:
    """消息去重器"""
    
    def __init__(self, ttl_seconds: int = 300):
        """
        初始化消息去重器
        
        Args:
            ttl_seconds: 消息ID缓存的生存时间（秒），默认5分钟
        """
        self.ttl_seconds = ttl_seconds
        self._processed_messages: Dict[str, Dict] = {}  # msgid -> {timestamp, response}
        self._lock = threading.RLock()  # 线程安全锁
    
    def check_duplicate(self, msgid: str) -> Tuple[bool, Optional[str]]:
        """
        检查消息是否重复，并返回缓存的回复内容
        
        Args:
            msgid: 消息ID
            
        Returns:
            Tuple[bool, Optional[str]]: (是否重复, 缓存的回复内容)
        """
        with self._lock:
            current_time = time.time()
            
            # 清理过期记录
            self._cleanup_expired(current_time)
            
            # 检查是否已处理过
            if msgid in self._processed_messages:
                cached_response = self._processed_messages[msgid].get('response')
                logger.warning(f"[消息去重] 🔄 检测到重复消息: {msgid}, 返回缓存回复")
                return True, cached_response
            
            # 记录新消息（暂时不存储回复内容）
            self._processed_messages[msgid] = {
                'timestamp': current_time,
                'response': None
            }
            logger.debug(f"[消息去重] ✅ 新消息已记录: {msgid}")
            return False, None
    
    def store_response(self, msgid: str, response: str) -> None:
        """
        存储消息的回复内容
        
        Args:
            msgid: 消息ID
            response: 回复内容
        """
        with self._lock:
            if msgid in self._processed_messages:
                self._processed_messages[msgid]['response'] = response
                logger.debug(f"[消息去重] 💾 存储回复内容: {msgid}")
    
    def is_duplicate(self, msgid: str) -> bool:
        """
        检查消息是否重复（保持向后兼容）
        
        Args:
            msgid: 消息ID
            
        Returns:
            bool: True表示重复消息，False表示新消息
        """
        is_dup, _ = self.check_duplicate(msgid)
        return is_dup
    
    def _cleanup_expired(self, current_time: float) -> None:
        """
        清理过期的消息记录
        
        Args:
            current_time: 当前时间戳
        """
        expired_keys = []
        for msgid, data in self._processed_messages.items():
            if current_time - data['timestamp'] > self.ttl_seconds:
                expired_keys.append(msgid)
        
        if expired_keys:
            for key in expired_keys:
                del self._processed_messages[key]
            logger.debug(f"[消息去重] 🧹 清理过期记录: {len(expired_keys)}条")
    
    def get_stats(self) -> Dict[str, int]:
        """
        获取去重器统计信息
        
        Returns:
            Dict: 包含缓存消息数量等统计信息
        """
        with self._lock:
            current_time = time.time()
            self._cleanup_expired(current_time)
            
            return {
                "cached_messages": len(self._processed_messages),
                "ttl_seconds": self.ttl_seconds
            }
    
    def clear_cache(self) -> None:
        """清空所有缓存"""
        with self._lock:
            cleared_count = len(self._processed_messages)
            self._processed_messages.clear()
            logger.info(f"[消息去重] 🗑️ 清空缓存，共清理{cleared_count}条记录")


# 全局去重器实例
_global_deduplicator = None
_dedup_lock = threading.Lock()


def get_message_deduplicator() -> MessageDeduplicator:
    """
    获取全局消息去重器实例（单例模式）
    
    Returns:
        MessageDeduplicator: 消息去重器实例
    """
    global _global_deduplicator
    
    if _global_deduplicator is None:
        with _dedup_lock:
            if _global_deduplicator is None:
                _global_deduplicator = MessageDeduplicator()
    
    return _global_deduplicator